# -*- coding: utf-8 -*-
# @Time : 2021/3/29 21:43
# @Author : Dong
# @File : demo_one.py
import logging
from logging.handlers import RotatingFileHandler

from requests.exceptions import RequestException   # 抓取报错
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from apscheduler.schedulers.blocking import BlockingScheduler

import config
from send_email import send_email

def log_file(LEVEL_NAME):
    # 设置日志的记录等级          # 调试debug级 , DEBUG < INFO < WARNING < ERROR
    logging.basicConfig(level=LEVEL_NAME)  # 一旦设置了级别，大于等于该级别的信息全部都会输出
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("../logs/logs.txt", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


log_file(logging.INFO)

def get(browser, url, retry=0):
    try:
        browser.get(url)
        return True
    except Exception as e:
        print(e)
        retry += 1
        if retry <= 3:
            return get(browser, url, retry)
        return False



def search(browser, wait):

    try:

        get_result = get(browser, config.baseurl)
        if get_result is False:
            send_email("网站访问失败", "访问%s失败" % config.baseurl)
            return

        login_btn = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="gatsby-focus-wrapper"]/div/header/div[2]/div/div[2]/div[1]/a[2]')))  # 获取搜索框
        login_btn.click()

        handles = browser.window_handles  # 获取当前浏览器的所有窗口句柄
        if len(handles) >= 2:
            browser.switch_to.window(handles[-1])

        username_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mui-1')))  # 获取搜索框
        passwd_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mui-2')))  # 获取搜索框
        login = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#mui-3')))  # 获取搜索按钮
        username_input.send_keys(config.usrename)  # 输入要搜索的
        passwd_input.send_keys(config.passwd)  # 输入要搜索的
        login.click()

        # 垃圾窗口删除
        # try:
        #     close_rubbish_windows = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "smcx-modal-close")))
        #     close_rubbish_windows.click()
        # except TimeoutException as e:
        #     print("未找到垃圾窗口")

        style_option = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="root"]/div[2]/main/div/div[2]/div/div[2]/div/div[1]/div[3]/div[4]/div[2]')))
        style_option.click()
        # html = browser.page_source  # 获取整个页面

        get_account = get(browser, config.account_url)
        if not get_account:
            send_email("获取账号信息失败", "访问%s失败" % config.account_url)
            return
        if get_account:
            import re
            import json
            match_account = re.search(".*?(\[.*?\}])", browser.page_source)
            if match_account.group(1):
                account = json.loads(match_account.group(1))
                for i in account:
                    yield i
        # cookie_list = browser.get_cookies()
        # cookies = ";".join([item["name"] + "=" + item["value"] + "" for item in cookie_list])

        # headers = {
        #     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
        # }
        # for i in cookies:
        #     headers[i.get("name")] = i.get("value")

        # requests.get("", headers=headers)
        # 解析
        # html_tree = etree.parse(html, etree.HTMLParser())

        # result = html_tree.xpath('//*')

    except RequestException as e:
        logging.info(e)
        return search(browser, wait)

# #mui-1
# #mui-2
# //*[@id="root"]/div[2]/main/div/div[2]/div/div[2]/div/div[1]/div[3]/div[4]/div[2]
# https://my.extrading.pro/v4/wta-api/async/personal_area/account?show_partner=True&show_crypto=True&show_investor=True

def main():
    # .PhantomJS 是后台运行 需要另外下载一个驱动 还有一些配置在config中
    # browser2 = webdriver.PhantomJS(service_args=config.SERVICE_ARGS)
    # browser2.set_window_size(1400,900)  # 窗口大小

    chrome_option = webdriver.ChromeOptions()
    # chrome_option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 以开发者模式
    chrome_option.add_argument('--proxy-server=https://sub.bxy.org.uk/api/v1/client/subscribe?token=5fbac7c62289d40b2efa40200dc6123e')
    # browser = webdriver.Chrome(options=chrome_option)
    browser = webdriver.Chrome(options=chrome_option)


    wait = WebDriverWait(browser, 50)  # 等待加载时间
    browser.implicitly_wait(50)

    for account_value in filter(
        lambda x: x.get("account_login") in config.account,
            search(browser, wait)
    ):
        logging.info("账号全部参数为: {}".format(account_value))
        # print(account_value)
        fay_money = float(account_value.get("equity")) - float(account_value.get("withdrawable"))
        imprest_percent = round(float(account_value.get("equity")) / fay_money * 100)
        # print(account_value.get("account_login")," ================ ", account_value, fay_money, imprest_percent)
        if imprest_percent < 2000:
            send_email("{}账号面临风险".format(account_value.get("account_login")), "预付款比例为 : {}\n 全部参数为: {}".format(imprest_percent, account_value))
            logging.info("{}账号面临风险 预付款比例为 : {}\n 全部参数为: {}".format(account_value.get("account_login"), imprest_percent, account_value))

    browser.quit()

if __name__ == '__main__':
    # 每个五秒运行一次函数
    sched = BlockingScheduler()
    # 不带参数和和带有参数的函数
    sched.add_job(func=main, trigger='interval', seconds=60*20)
    sched.start()
    # main()

